package com.nbjtjc.safe.oss.controller;

import com.nbjtjc.safe.oss.service.OSSFactory;
import com.nbjtjc.safe.Exception.SafeException;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.util.BaiduOCRUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @auther guqianbin
 * @date 2018/11/21 10:48
 **/
@RestController
@CrossOrigin("*")
@RequestMapping("sys/oss")
public class OssController {

    private static Logger logger= LoggerFactory.getLogger(OssController.class);
    @Autowired
    private OSSFactory ossFactory;

    @Autowired
    private BaiduOCRUtil baiduOCRUtil;
    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new SafeException("上传文件不能为空");
        }
        file.transferTo(new File("d://"+file.getOriginalFilename()));
        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = ossFactory.build().uploadSuffix(new FileInputStream(new File("d://"+file.getOriginalFilename())), suffix);
        return Result.success(url);
    }

    @RequestMapping("/fileKey")
    public Result getFileKey(){
        Result result=new Result();
        result.setData(baiduOCRUtil.getFileKey());
        return result;
    }

    @GetMapping("/sign")
    @ApiOperation("需要传realName：文件的真实名字，contentId：绑定的内容id，contentType")
    public void sign(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String result=ossFactory.build().sign(request,response);
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            logger.warn(key+":"+value);
        }
        Map<String,String[]> stringMap= request.getParameterMap();
        Iterator iterator= stringMap.keySet().iterator();
        while (iterator.hasNext()){
            logger.warn(stringMap.get(iterator.next().toString()).toString());
        }
        this.response(request,response,result);
    }

    /**
     * 回调方法，阿里云会调用
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/ossCallback",method = {RequestMethod.POST,RequestMethod.GET})
    public void ossCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            logger.error(key+":"+value);
        }
        Map<String,String[]> stringMap= request.getParameterMap();
        Iterator iterator= stringMap.keySet().iterator();
        while (iterator.hasNext()){
            String key=iterator.next().toString();
            String[] strs=stringMap.get(key);
            for(int i=0;i<strs.length;i++){
                logger.error("参数 "+key+":"+i+":"+strs[i]);
            }
        }
        ossFactory.build().callback(response,request);
    }



    /**
     * 服务器响应结果
     */
    private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
        String callbackFunName = request.getParameter("callback");
        if (callbackFunName == null || callbackFunName.equalsIgnoreCase(""))
            response.getWriter().println(results);
        else
            response.getWriter().println(callbackFunName + "( " + results + " )");
        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
    }
}
